<script setup>
import {
  getBizProductInfo,
  addBizProductInfo,
  updateBizProductInfo,
  findMaxSort
} from "@/api/biz/bizProductInfo";
import { delBizProductSku } from "@/api/biz/bizProductSku";
import { listRubbishTypeTree } from "@/api/biz/bizRubbishType";
import storage from "@/utils/storage";
import { TOKEN } from "@/store/mutation-types";
import draggable from "vuedraggable";

const props = defineProps({
  id: {
    type: [Number, String],
    default: ""
  },
  type: {
    type: [Number, String],
    default: ""
  }
});
const fileHeahers = ref({
  url: import.meta.env.VITE_APP_API_BASEURL + "/common/upload",
  headers: {
    Authorization: "Bearer " + storage.local.get(TOKEN)
  }
});
const formRef = ref();
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const dialogDetailsImageUrl = ref("");
const dialogDetailsVisible = ref(false);
const data = ref({
  loading: false,
  form: {
    id: props.id,
    showIndex: 0,
    status: 0,
    productSkuList: [],
    indexImg: [],
    detailsInfo: [],
    isMiaosha: 0,
    isFirst: 0
  },
  rules: {},
  deptTreeList: [],
  activeName: "first",
  fileList: [],
  zhuImageList: [],
  showDraggable: true,
  detailFileList: []
});

onMounted(() => {
  if (data.value.form.id != "") {
    getInfo();
  } else {
    findMaxSort().then((res) => {
      data.value.form.sort = res.data;
    });
  }

  listRubbishTypeTree("", 3, props.type).then((res) => {
    data.value.deptTreeList = getTreeData(res.data);
  });
  console.log("xxxx001", props.type);
});

function getTreeData(data) {
  return data.map((tree) => {
    tree.id = tree.id;
    tree.label = tree.title;
    if (tree.children) {
      tree.children = getTreeData(tree.children);
    }
    return tree;
  });
}
function handleRemove(uploadFile, uploadFiles) {
  console.log(uploadFile, uploadFiles);
  if (uploadFiles.length > 0) {
    data.value.form.indexImg = uploadFiles.map((item) => {
      return item.url;
    });
  } else {
    data.value.form.indexImg = [];
  }

  console.log("item.url", data.value.form.indexImg);
}

function handleDetailsRemove(uploadFile, uploadFiles) {
  console.log(uploadFile, uploadFiles);
  if (uploadFiles.length > 0) {
    data.value.form.detailsInfo = uploadFiles.map((item) => {
      return item.url;
    });
  } else {
    data.value.form.detailsInfo = [];
  }
  console.log("item.url", data.value.form.detailsInfo);
}

function getInfo() {
  data.value.loading = true;
  getBizProductInfo(props.id).then((res) => {
    data.value.loading = false;
    data.value.form = res.data;
    // props.value.type = data.value.form.type;
    if (res.data.indexImg && res.data.indexImg != "") {
      data.value.form.indexImg = JSON.parse(res.data.indexImg);
      data.value.fileList = data.value.form.indexImg.map((item, index) => {
        return { name: item, url: item, uid: "00" + index, id: index };
      });
      console.log(data.value.fileList);
    } else {
      data.value.form.indexImg = [];
    }

    if (res.data.detailsInfo && res.data.detailsInfo != "") {
      data.value.form.detailsInfo = JSON.parse(res.data.detailsInfo);
      data.value.detailFileList = data.value.form.detailsInfo.map(
        (item, index) => {
          return { name: item, url: item, uid: "00" + index, id: index };
        }
      );
      console.log(data.value.fileList);
    } else {
      data.value.form.detailsInfo = [];
    }
  });
}
function handlePictureCardPreview(uploadFile) {
  dialogImageUrl.value = uploadFile.url;
  console.log(uploadFile.url);
  dialogVisible.value = true;
}

function handleDetailsPictureCardPreview(uploadFile) {
  dialogDetailsImageUrl.value = uploadFile.url;
  console.log(uploadFile.url);
  dialogDetailsVisible.value = true;
}

function handleDetailsImg(response, file, fileList) {
  data.value.form.detailsInfo.push(file.response.data.url);
}
function deleDetailsImg(data, index) {
  data.value.form.detailsInfo.splice(index, 1);
  data.detailFileList.splice(index, 1);
}

function handleIndexImg(response, file, fileList) {
  data.value.form.indexImg.push(file.response.data.url);
}

function deleImg(data, index) {
  data.value.form.indexImg.splice(index, 1);
  data.fileList.splice(index, 1);
}

//拖拽开始的事件
const onStart = () => {
  console.log("开始拖拽");
};

//拖拽结束的事件
const onEnd = () => {
  console.log("结束拖拽");
  data.value.form.indexImg = data.value.fileList.map((item) => {
    return item.url;
  });
};

// 添加产品的SKU
function handlAddProductSku() {
  var sku = {
    skuImg: "",
    stock: 0,
    price: 0.0,
    salePrice: 0.0,
    upc: "",
    isEdit: true,
    unit: "",
    qySkuId: "",
    miaoshaPrice: 0.0,
    firstPrice: 0.0
  };
  data.value.form.productSkuList.push(sku);
}
// 删除行
function onDel(row, index) {
  if (row.id) {
    delBizProductSku(row.id).then((res) => {
      if (res.code == 200) {
        ElMessage.success({
          message: "保存成功",
          center: true
        });
        data.value.form.productSkuList.splice(index, 1);
      }
    });
  } else {
    data.value.form.productSkuList.splice(index, 1);
  }
}
// 编辑行
function onEdit(row) {
  row.isEdit = true;
}
// 保存行
function onSave(row) {
  row.isEdit = false;
}
// 上传sku 路径
function handleAvatarSuccess(response, file, fileList, row) {
  // data.value.form.imageUrl = file.response.data.url;
  console.log(row);
  row.skuImg = file.response.data.url;
}
defineExpose({
  submit(callback) {
    let rubbishTypeNames = data.value.deptTreeList.map((item) => {
      if (data.value.form.rubbishTypeId == item.id) {
        return item.label;
      }
    });
    data.value.form.rubbishTypeName = rubbishTypeNames[0];
    if (data.value.form.id == "") {
      formRef.value.validate((valid) => {
        if (valid) {
          data.value.form.type = props.type;
          data.value.form.indexImg = JSON.stringify(data.value.form.indexImg);
          data.value.form.detailsInfo = JSON.stringify(
            data.value.form.detailsInfo
          );
          addBizProductInfo(data.value.form).then(() => {
            ElMessage.success({
              message: "保存成功",
              center: true
            });
            callback && callback();
          });
        }
      });
    } else {
      formRef.value.validate((valid) => {
        if (valid) {
          data.value.form.type = props.type;
          data.value.form.indexImg = JSON.stringify(data.value.form.indexImg);
          data.value.form.detailsInfo = JSON.stringify(
            data.value.form.detailsInfo
          );
          updateBizProductInfo(data.value.form).then(() => {
            ElMessage.success({
              message: "修改成功",
              center: true
            });
            callback && callback();
          });
        }
      });
    }
  }
});
</script>

<template>
  <div v-loading="data.loading">
    <el-form
      ref="formRef"
      :model="data.form"
      :rules="data.rules"
      label-width="120px"
      label-suffix=" "
      label-position="top"
      style="padding: 0 20px"
    >
      <el-row :gutter="30">
        <el-col :span="5">
          <el-form-item label="产品分类" prop="rubbishTypeId">
            <el-tree-select
              v-model="data.form.rubbishTypeId"
              :data="data.deptTreeList"
              :default-expand-all="true"
              node-key="id"
              :check-strictly="true"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="产品标题" prop="title">
            <el-input
              placeholder="请输入产品标题（详情标题）"
              v-model="data.form.title"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产品副标题" prop="fuTitle">
            <el-input
              placeholder="请输入产品副标题（简介标题）"
              v-model="data.form.fuTitle"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="品牌名称" prop="brand" v-if="props.type == 1">
            <el-input placeholder="请输入品牌名称" v-model="data.form.brand" />
          </el-form-item>
          <el-form-item label="标题简介" prop="brand" v-if="props.type == 0">
            <el-input placeholder="请输入品牌名称" v-model="data.form.brand" />
          </el-form-item>
        </el-col>

        <!-- <el-col :span="12">
          <el-form-item label="关键字" prop="keyWord">
            <el-input
              placeholder="请输入关键字（如：夏季、健康食品、绿色食品）"
              v-model="data.form.keyWord"
            />
          </el-form-item>
        </el-col> -->
        <el-col :span="4" v-if="props.type == 0">
          <el-form-item label="可洗范围" prop="xihuScope">
            <el-input
              placeholder="请输入产品可洗范围"
              v-model="data.form.xihuScope"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" v-if="props.type == 0">
          <el-form-item label="洗护时效" prop="xihuTimes">
            <el-input
              placeholder="请输入产品洗护时效"
              v-model="data.form.xihuTimes"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4" v-if="props.type == 0">
          <el-form-item label="洗护工艺" prop="xihuTechnology">
            <el-input
              placeholder="请输入产品洗护工艺"
              v-model="data.form.xihuTechnology"
            />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="已售数量" prop="outCount">
            <el-input
              placeholder="请输入已售数量"
              v-model="data.form.outCount"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="首页推荐" prop="showIndex">
            <el-radio-group v-model="data.form.showIndex">
              <el-radio-button label="0">是</el-radio-button>
              <el-radio-button label="1">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="是否上架" prop="status">
            <el-radio-group v-model="data.form.status">
              <el-radio-button label="0">是</el-radio-button>
              <el-radio-button label="1">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="首单优惠" prop="isFirst">
            <el-radio-group v-model="data.form.isFirst">
              <el-radio-button label="0">否</el-radio-button>
              <el-radio-button label="1">是</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="排序(升序)" prop="sort">
            <el-input-number placeholder="序号" v-model="data.form.sort" />
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="是否秒杀" prop="isMiaosha">
            <el-radio-group v-model="data.form.isMiaosha">
              <el-radio-button label="0">否</el-radio-button>
              <el-radio-button label="1">是</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="5" v-if="data.form.isMiaosha == 1">
          <el-form-item label="秒杀开始时间" prop="sort">
            <el-date-picker
              v-model="data.form.beginMiaoshaTime"
              type="datetime"
              placeholder="秒杀开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :span="5" v-if="data.form.isMiaosha == 1">
          <el-form-item label="秒杀结束时间" prop="sort">
            <el-date-picker
              v-model="data.form.endMiaoshaTime"
              type="datetime"
              placeholder="秒杀结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="24" style="min-height: 580px">
          <el-tabs
            v-model="data.activeName"
            class="demo-tabs"
            @tab-click="handleClick"
          >
            <el-tab-pane name="first" label="产品主图">
              <span style="color: #999"
                >最多上传6张主图，建议图片像素（450px*450px）</span
              >
              <el-upload
                v-model:file-list="data.fileList"
                :action="fileHeahers.url"
                :headers="fileHeahers.headers"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="handleIndexImg"
              >
                <svg-icon
                  style="color: #409eff; font-size: 32px"
                  name="ep:plus"
                >
                </svg-icon>
              </el-upload>
              <span style="color: rgb(215 78 78)"
                >提示：拖动下面图片可以调整图片顺序</span
              >
              <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="产品主图" />
              </el-dialog>
              <draggable
                :list="data.fileList"
                ghost-class="ghost"
                chosen-class="chosenClass"
                animation="300"
                @start="onStart"
                @end="onEnd"
              >
                <template #item="{ element }">
                  <div class="img-wrapper">
                    <el-image :src="element.url"> </el-image>
                  </div>
                </template>
              </draggable>
            </el-tab-pane>
            <el-tab-pane name="second" label="产品详情">
              <!-- <editor v-model="data.form.detailsInfo" /> -->
              <el-upload
                v-model:file-list="data.detailFileList"
                :action="fileHeahers.url"
                :headers="fileHeahers.headers"
                list-type="picture-card"
                :on-preview="handleDetailsPictureCardPreview"
                :on-remove="handleDetailsRemove"
                :on-success="handleDetailsImg"
              >
                <svg-icon
                  style="color: #409eff; font-size: 32px"
                  name="ep:plus"
                >
                </svg-icon>
              </el-upload>

              <el-dialog v-model="dialogDetailsVisible">
                <img w-full :src="dialogDetailsImageUrl" alt="产品主图" />
              </el-dialog>
            </el-tab-pane>
            <el-tab-pane name="third" label="产品规格">
              <el-button type="primary" @click="handlAddProductSku"
                >添加规格</el-button
              >
              <p></p>
              <el-table :data="data.form.productSkuList" :border="true">
                <el-table-column
                  label="图片(150px)"
                  prop="skuImg"
                  align="center"
                >
                  <template #default="scope">
                    <el-upload
                      class="avatar-uploader"
                      :action="fileHeahers.url"
                      :headers="fileHeahers.headers"
                      :show-file-list="false"
                      :on-success="
                        (response, file, fileList) =>
                          handleAvatarSuccess(
                            response,
                            file,
                            fileList,
                            scope.row
                          )
                      "
                    >
                      <img
                        :src="scope.row.skuImg"
                        class="avatar"
                        v-if="scope.row.skuImg"
                        style="width: 58px; height: 58px"
                      />

                      <svg-icon
                        v-else
                        class="el-icon-plus avatar-uploader-icon"
                        name="ep:upload-filled"
                        style="font-size: 24px"
                      />
                    </el-upload>
                  </template>
                </el-table-column>
                <el-table-column label="规格" prop="unit" align="right">
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.unit"
                      v-if="scope.row.isEdit"
                    ></el-input>
                    <span v-else>{{ scope.row.unit }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="库存数量"
                  prop="stock"
                  align="right"
                  width="100px"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.stock"
                      v-if="scope.row.isEdit"
                    ></el-input>
                    <span v-else>{{ scope.row.stock }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="原价（元）"
                  prop="price"
                  align="right"
                  width="100px"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.price"
                      v-if="scope.row.isEdit"
                    ></el-input>
                    <span v-else>{{
                      parseFloat(scope.row.price).toFixed(2)
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="折扣价格（元）"
                  prop="salePrice"
                  align="right"
                  width="130px"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.salePrice"
                      v-if="scope.row.isEdit"
                    ></el-input>
                    <span v-else>{{
                      parseFloat(scope.row.salePrice).toFixed(2)
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="秒杀价格（元）"
                  prop="salePrice"
                  align="right"
                  width="130px"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.miaoshaPrice"
                      v-if="scope.row.isEdit"
                    ></el-input>
                    <span v-else>{{
                      parseFloat(
                        scope.row.miaoshaPrice ? scope.row.miaoshaPrice : 0
                      ).toFixed(2)
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="首单价格（元）"
                  prop="salePrice"
                  align="right"
                  width="130px"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.firstPrice"
                      v-if="scope.row.isEdit"
                    ></el-input>
                    <span v-else>{{
                      parseFloat(
                        scope.row.firstPrice ? scope.row.firstPrice : 0
                      ).toFixed(2)
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="SKUID"
                  prop="qySkuId"
                  align="right"
                  width="100px"
                >
                  <template #default="scope">
                    <el-input
                      v-model="scope.row.qySkuId"
                      v-if="scope.row.isEdit"
                    ></el-input>
                    <span v-else>{{ scope.row.qySkuId }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  align="center"
                  width="160px"
                  type="index"
                >
                  <template #default="scope, index">
                    <el-button-group>
                      <el-button
                        type="primary"
                        size="small"
                        text
                        @click="onEdit(scope.row)"
                        v-if="!scope.row.isEdit"
                      >
                        <template #icon>
                          <el-icon>
                            <svg-icon name="ant-design:edit-filled" />
                          </el-icon>
                        </template>
                        编 辑</el-button
                      >
                      <el-button
                        type="primary"
                        size="small"
                        text
                        @click="onSave(scope.row)"
                        v-else
                      >
                        <template #icon>
                          <el-icon>
                            <svg-icon name="ep:select" />
                          </el-icon>
                        </template>
                        保 存</el-button
                      >
                      <el-button
                        type="danger"
                        text
                        size="small"
                        @click="onDel(scope.row, scope.$index)"
                      >
                        <template #icon>
                          <el-icon>
                            <svg-icon name="ep:close-bold" />
                          </el-icon>
                        </template>
                        删除
                      </el-button>
                    </el-button-group>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<style lang="less" scoped>
.img-list {
  display: inline-block;
}
.img-wrapper {
  float: left;
  position: relative;
  margin-right: 20px;
  margin-bottom: 20px;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  width: 148px;
  height: 148px;
  overflow: hidden;
  &:hover {
    .operate-wrap {
      display: block;
    }
  }
}
.operate-wrap {
  display: none;
}
.operate-bg {
  background: #000;
  width: 148px;
  height: 148px;
  opacity: 0.4;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 8;
}
.del-icon {
  position: absolute;
  top: 0;
  right: 36px;
  font-size: 25px;
  line-height: 142px;
  color: #fff;
  z-index: 10;
}
.preview-icon {
  position: absolute;
  top: 0;
  left: 36px;
  font-size: 25px;
  line-height: 142px;
  color: #fff;
  z-index: 10;
}
</style>
